package com.alstudio.utils.android;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.alstudio.net.protocol.xmpp.data.User;

/**
 * ALContactsManager 实现快速读取本地联系人。通过后台异步任务进行读取，完毕后通过回调通知UI
 * @author Alonso Lee
 *
 */
public class ALContactsManager {

	private static ALContactsManager manager;

	public static ALContactsManager getLocalContactsManager() {
		if (manager == null) {
			manager = new ALContactsManager();
		}
		return manager;
	}

	/**
	 * 读取本地联系人
	 * 
	 * @param activity
	 * @param callback
	 */
	public void loadLocalContacts(Activity activity,
			LoadLocalContactCallback callback) {
		new ReadContactsTask(activity, callback).execute();
	}

	private class ReadContactsTask extends
			AsyncTask<Void, Void, ArrayList<User>> {

		private Activity mActivity;
		private LoadLocalContactCallback mCallback;

		public ReadContactsTask(Activity activity,
				LoadLocalContactCallback callback) {
			// TODO Auto-generated constructor stub
			mActivity = activity;
			mCallback = callback;
		}

		@Override
		protected ArrayList<User> doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<User> contacts = new ArrayList<User>();
			try {
				loadAllSimContacts(mActivity, contacts);
				loadPhoneContacts(mActivity, contacts);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				contacts = null;
			}
			return contacts;
		}

		@Override
		protected void onPostExecute(ArrayList<User> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (mCallback != null) {
				if (result != null) {
					mCallback.onLoadFinish(result);
				} else {
					mCallback.onError();
				}
			}
		}
	}

	/**
	 * 读取手机中联系人列表
	 * 
	 * @param activity
	 * @param result
	 */
	private void loadPhoneContacts(Activity activity, ArrayList<User> result) {
		// 读取电话本中的联系人信息
		Cursor cur = activity.getContentResolver().query(
				Uri.parse("content://com.android.contacts/contacts"), null,
				null, null, null);

		// 循环遍历
		if (cur.moveToFirst()) {
			int idColumn = cur.getColumnIndex("_id");
			int displayNameColumn = cur.getColumnIndex("display_name");

			String contactId;
			String disPlayName;
			int phoneCount = 0;
			Cursor phones;

			String phoneNumber;
			User u = null;

			do {
				// 获得联系人的ID号
				contactId = cur.getString(idColumn);
				// 获得联系人姓名
				disPlayName = cur.getString(displayNameColumn);
				phoneCount = cur.getInt(cur.getColumnIndex("has_phone_number"));

				if (phoneCount > 0) {
					// 获得联系人的电话号码
					phones = activity
							.getContentResolver()
							.query(Uri
									.parse("content://com.android.contacts/data/phones"),
									null, "contact_id" + " = " + contactId,
									null, null);
					phones.moveToFirst();

					do {
						// 遍历所有的电话号码
						phoneNumber = phones.getString(phones
								.getColumnIndex("data1"));
						u = new User();
						u.setPhone(phoneNumber);
						if (TextUtils.isEmpty(disPlayName)) {
							disPlayName = phoneNumber;
						}
						u.setNick(disPlayName);
						u.setJid(phoneNumber);
						if (!result.contains(u)) {
							result.add(u);
						}
					} while (phones.moveToNext());
					phones.close();
				}

			} while (cur.moveToNext());

		}
		cur.close();
	}

	private void loadAllSimContacts(Activity activity, ArrayList<User> result) { // 获取各种型号SIM卡上的信息

		loadAllSimCardContacts(activity, "content://icc/adn", result);
		loadAllSimCardContacts(activity, "content://sim/adn", result);
		loadAllSimCardContacts(activity, "content://icc/fdn", result);
		loadAllSimCardContacts(activity, "content://sim/fdn", result);
		loadAllSimCardContacts(activity, "content://contacts/phones", result);
	}

	private void loadAllSimCardContacts(Activity activity, String add,
			ArrayList<User> result) {
		// 读取SIM卡手机号,有几种可能:content://icc/adn与content://sim/adn
		Intent intent = new Intent();
		intent.setData(Uri.parse(add));
		Uri uri = intent.getData();
		Cursor mCursor = activity.getContentResolver().query(uri, null, null,
				null, null);
		int nameFieldColumnIndex;
		String contactName;
		int numberFieldColumnIndex;
		String userNumber;
		User u = null;
		// 没差sim 卡？
		if (mCursor == null) {
			return;
		}
		while (mCursor.moveToNext()) {
			// 取得联系人名字
			nameFieldColumnIndex = mCursor.getColumnIndex("name");
			contactName = mCursor.getString(nameFieldColumnIndex);
			// 取得电话号码
			numberFieldColumnIndex = mCursor.getColumnIndex("number");
			userNumber = mCursor.getString(numberFieldColumnIndex);

			u = new User();
			u.setPhone(userNumber);
			if (TextUtils.isEmpty(contactName)) {
				contactName = userNumber;
			}
			u.setNick(contactName);
			u.setJid(userNumber);
			if (!result.contains(u)) {
				result.add(u);
			}
		}
		mCursor.close();
	}

	public interface LoadLocalContactCallback {
		public void onLoadFinish(ArrayList<User> contacts);

		public void onError();
	}
}
